'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');
class BooksController extends Controller {

  async list() {
    const { ctx } = this;
    try {
      const list = await ctx.model.Books.findAll();
      ctx.helper.renderSuccess(ctx, { data: list });
    } catch (err) {
      ctx.helper.renderFail(ctx, { message: err });
    }

  }

  async findOne() {
    const { ctx } = this;
    const { uuid } = ctx.query;
    try {
      const details = await ctx.model.Books.findOne({
        where: {
          uuid: {
            [Op.eq]: uuid,
          },
        },
      });
      ctx.helper.renderSuccess(ctx, { data: details });
    } catch (err) {
      ctx.helper.renderFail(ctx, { message: err });
    }
  }

  async create() {
    const { ctx } = this;
    const addInfo = ctx.request.body || {};

    // 测试代码
    // const demo = {
    //   name: "冲上云霄*珍本",
    //   counts: 300,
    //   last_couonts: 110,
    //   intro: '心若向阳，一路芬芳',
    //   user_id: 1
    // }
    const demo = {
      name: addInfo.name,
      counts: addInfo.counts,
      last_couonts: addInfo.last_couonts,
      intro: addInfo.intro,
      user_id: addInfo.user_id,
    };
    try {
      if (addInfo.name) {
        const bookInfo = await ctx.model.Books.create({
          ...demo,
        });
        ctx.helper.renderSuccess(ctx, { data: bookInfo });
      } else {
        ctx.helper.renderSuccess(ctx, { message: '添加数据无效' });
      }
    } catch (err) {
      ctx.helper.renderFail(ctx, { message: err });
    }
  }

  async delete() {
    const { ctx } = this;
    const { uuid } = ctx.params;
    try {
      await ctx.model.Books.destroy({
        where: {
          uuid,
        },
      });
      ctx.helper.renderSuccess(ctx, { message: '删除成功' });
    } catch (err) {
      ctx.helper.renderFail(ctx, { message: err });
    }
  }

  async update() {
    const { ctx } = this;
    // const updateInfo, { uuid} = ctx.request.body;
    const updateInfo = {
      intro: '我有一次修改了信息',
    };
    const uuid = '2e099cbd-17ab-4408-8a7f-bf98fe2a37ce';
    try {
      const info = await ctx.model.Books.update({
        ...updateInfo,
      }, {
        where: {
          uuid,
        },
      });
      ctx.helper.renderSuccess(ctx, { data: info });
    } catch (err) {
      ctx.helper.renderFail(ctx, { message: err });
    }
  }

}

module.exports = BooksController;
